function formSubmit(f, b, v) {
    document.getElementById(b).value = v;
    document.getElementById(f).submit();
}

function decode(s) {
	if (typeof s === "string") return s.split(" u&quot;&#39;").join(' "\'').split("&quot;").join('"').split(" u&#39;").join(' "').split("&#39;").join('"').split("None").join('null').split("False").join('false').split("True").join('true');
}

function setVNClass(p_vnc)
{
	var r = '';
	if (typeof p_vnc === "string") {
	  r = decode(p_vnc);
	  sessionStorage.setItem('VNC', r);
	}
}

function getVNClass()
{
	var r = sessionStorage.getItem('VNC');
    return r;
}

// exp ::- [{'op':op, 'args':arg}] <-- p_exp
// op  ::- 'and' | 'or'
// arg  ::- [{'value': (<Value> | exp), 'type':type}] 
// type ::- 'exp'| <x>
function restrictionToString(p_exp) {
  var s = "";
  if (p_exp) {
    for (a=0; a<p_exp.length; a++) {
      var le = p_exp[a];
      var o = le.op;
      var d = " ";
      if (o == "and") { d = " & "; }
      else if (o == "or") { d = " | "; }
      if (le.args) {
        for (var i=0; i<le.args.length; i++) {
          var arg = le.args[i];
          if (s.length > 0) { s = s + d; }
          if (arg.type == "exp") {
            s = s + " (" + restrictionToString(arg.value) + ")"
          }
          else {
            s = s + arg.value + arg.type;
          }
        }
      }
    }
  }
  return s;
}

function verbalizeRestriction(p_json, box) {
    var r = decode(p_json);
    var obj = JSON.parse(r);
    r = restrictionToString(obj);
    if (r.length > 0 && box) r = "[" + r + "]"
    return r;
}

// [{'phrases': [{'restr': [], 'select': [], 'type': 'NP', 'pos': 0, 'value': 'Agent'}], 'verbPosition': 0, 'isOrdered': 'No'}]
function verbalizeSyntax(p_json) {
	var r = decode(p_json);
    var obs = JSON.parse(r);
    r = "";
    for (var i=0; i<obs.length; i++) {
    	if (r.length > 0) r = r + " | ";
    	if (obs[i].isOrdered == "No") r = r + "Perm (";
    	for (var j=0; j<obs[i].phrases.length; j++) {
    		var pos = obs[i].phrases[j];
    		if (j > 0) r = r + " ";
    		if (pos.type == "PREP") {
		    if (pos.select.length > 0) {
			if (pos.select[0].type == 'exp') {
			    r = r + "{{<span class=\"tooltip-test\" title=\"" + pos.type + "\">"+ restrictionToString(pos.select[0].value) +"</span>}}";
			} else {
			    r = r + "{{<span class=\"tooltip-test\" title=\"" + pos.type + "\">"+ pos.select[0].value + pos.select[0].type +"</span>}}";
			}
		    } else {
		        r = r + "{<span class=\"tooltip-test\" title=\"" + pos.type + "\">"+ pos.value +"</span>}";
		    }
		}
    		else if (!pos.value) r = r + pos.type;
    		else r = r + "<span class=\"tooltip-test\" title=\"" + pos.type + "\">" + pos.value + "</span>";
    		if (pos.restr.length > 0) r = r + " <" + restrictionToString(pos.restr) + ">";
    	}
    	if (obs[i].isOrdered == "No") r = r + ")";
    }
    return r;
}

// [{'predicates': [{'bool': False, 'args': [{'type': 'ThemRole', 'value': 'Agent'}, {'type': 'Event', 'value': 'E'}], 'type': 'cause'}]}]

function verbalizeSemanticsArgs(p_args) {
	var r = "";
	if (p_args) {
		for (var k=0; k<p_args.length; k++) {
			if (k > 0) r = r + ", ";
			r = r + p_args[k].value;
		}
	}
	return r;
}

function verbalizeSemantics(p_json) {
	var r = decode(p_json);
    var obs = JSON.parse(r);
    r = "";
    for (var i=0; i<obs.length; i++) {
    	if (r.length > 0) r = r + " | ";
    	for (var j=0; j<obs[i].predicates.length; j++) {
    		var pos = obs[i].predicates[j];
    		if (j > 0) r = r + " ";
    		if (pos.bool) r = r + "!";
    		r = r + pos.type + "(";
    		r = r + verbalizeSemanticsArgs(pos.args);
    		r = r + ")";
    	}
    }
    return r;
}

function verbalizeMember(p_json) {
    var r = decode(p_json);
    var obs = JSON.parse(r);
    r = '<strong>'+obs.name+'</strong> (';
    if (obs.wn != null) {
      wns = obs.wn.split(' ');
      for (i=0; i<wns.length;i++) {
        if (i>0) r = r + ', ';
        r = r + '<a href="http://wordnetweb.princeton.edu/perl/webwn?s='+obs.name+'&o6=1" target="_blank">'+wns[i]+'</a>';
      }
    }
    r = r + ') ';
    return r;
}

/* Button actions
 * 
 * In each modal form is: 
 * # hidden input "#id" which must refer to VNClass.id
 * # hidden input "#datatype" which value refers to object type
 */

$(document).on("click", ".open-addMemberModal", function () {
	var l_id = $(this).data('id');
    if (l_id != null) {
      $(".modal-body #id").val( l_id );
      $(".modal-body #member_id").val( -1 );
      $(".modal-body #name").val( null );
      $(".modal-body #wn").val( null );
      $(".modal-body #locwn").val( null );
      $(".modal-body #grouping").val( null );
	}
});

$(document).on("click", ".open-updMemberModal", function () {
	var l_id = $(this).data('id');
	var r = getVNClass()
	if (r.length > 0) {
      var vnc = JSON.parse(r);
      var obs = null;
      for (i=0; i<vnc.members.length; i++) {
    	  if (vnc.members[i].id == l_id) {
    		  obs = vnc.members[i];
    		  break;
    	  }
      }
      if (obs != null) {
        $(".modal-body #member_id").val( obs.id );
        $(".modal-body #id").val( obs.owner );
        $(".modal-body #name").val( obs.name );
        $(".modal-body #wn").val( obs.wn );
        $(".modal-body #locwn").val( obs.locwn );
        $(".modal-body #grouping").val( obs.grouping );
	  }
	}
});

$(document).on("click", ".open-delMemberModal", function () {
	var l_id = $(this).data('id');
	var r = getVNClass()
	if (r.length > 0) {
      var vnc = JSON.parse(r);
      var obs = null;
      for (i=0; i<vnc.members.length; i++) {
    	  if (vnc.members[i].id == l_id) {
    		  obs = vnc.members[i];
    		  break;
    	  }
      }
      if (obs != null) {
        $(".modal-body #member_id").val( obs.id );
        $(".modal-body #id").val( obs.owner );
        $(".modal-body #delObjectName").text( obs.name );
	  }
	}
});

$(document).on("click", ".open-addRoleModal", function () {
	var l_id = $(this).data('id');
    if (l_id != null) {
      $(".modal-body #id").val( l_id );
      $(".modal-body #role_id").val( -1 );
      $(".modal-body #role").val( null );
      $(".modal-body #position").val( null );
      $(".modal-body #role_restr").val( null );
	}
});

$(document).on("click", ".open-updRoleModal", function () {
	var l_id = $(this).data('id');
	var r = getVNClass()
	if (r.length > 0) {
      var vnc = JSON.parse(r);
      var obs = null;
      for (i=0; i<vnc.roles.length; i++) {
    	  if (vnc.roles[i].id == l_id) {
    		  obs = vnc.roles[i];
    		  break;
    	  }
      }
      if (obs != null) {
        $(".modal-body #role_id").val( obs.id );
        $(".modal-body #id").val( obs.owner );
        $(".modal-body #role").val( obs.role );
        $(".modal-body #position").val( obs.pos );
        l_restrs = JSON.stringify(obs.restrs)
        $(".modal-body #role_restr").val( verbalizeRestriction(l_restrs, false) );
	  }
	}
});

$(document).on("click", ".open-delRoleModal", function () {
	var l_id = $(this).data('id');
	var r = getVNClass()
	if (r.length > 0) {
      var vnc = JSON.parse(r);
      var obs = null;
      for (i=0; i<vnc.roles.length; i++) {
    	  if (vnc.roles[i].id == l_id) {
    		  obs = vnc.roles[i];
    		  break;
    	  }
      }
      if (obs != null) {
        $(".modal-body #role_id").val( obs.id );
        $(".modal-body #id").val( obs.owner );
        $(".modal-body #delObjectName").text( obs.name );
	  }
	}
});

$(document).on("click", ".open-addFrameModal", function () {
	var l_id = $(this).data('id');
    if (l_id != null) {
      $(".modal-body #id").val( l_id );
      $(".modal-body #frame_id").val( -1 );
      $(".modal-body #primary").val( null );
      $(".modal-body #secondary").val( null );
      $(".modal-body #descriptionNumber").val( null );
      $(".modal-body #xtag").val( null );
      $(".modal-body #example").val( null );
	}
});

$(document).on("click", ".open-updFrameModal", function () {
	var l_id = $(this).data('id');
	var r = getVNClass()
	if (r.length > 0) {
      var vnc = JSON.parse(r);
      var obs = null;
      for (i=0; i<vnc.frames.length; i++) {
    	  if (vnc.frames[i].id == l_id) {
    		  obs = vnc.frames[i];
    		  break;
    	  }
      }
      if (obs != null) {
        $(".modal-body #frame_id").val( obs.id );
        $(".modal-body #id").val( obs.owner );
        $(".modal-body #primary").val( obs.primary );
        $(".modal-body #secondary").val( obs.secondary );
        $(".modal-body #descriptionNumber").val( obs.descriptionNumber );
        $(".modal-body #xtag").val( obs.xtag );
        $(".modal-body #example").val( obs.example );
	  }
	}
});

$(document).on("click", ".open-delFrameModal", function () {
	var l_id = $(this).data('id');
	var r = getVNClass()
	if (r.length > 0) {
      var vnc = JSON.parse(r);
      var obs = null;
      for (i=0; i<vnc.frames.length; i++) {
    	  if (vnc.frames[i].id == l_id) {
    		  obs = vnc.frames[i];
    		  break;
    	  }
      }
      if (obs != null) {
        $(".modal-body #frame_id").val( obs.id );
        $(".modal-body #id").val( obs.owner );
        $(".modal-body #delObjectName").text( obs.primary );
	  }
	}
});

function GetHtml(template, table, fields) //Get the template and update the input field names
{
    var len = $(table).length;
    var $html = $(template).clone();
    for (var i=0;i<fields.length;i++) {
        var s = fields[i];
        var bn = $html.find('[name='+s+']')[0];
        if (bn != null) bn.name=s+'_'+len;
        var bi = $html.find('[id='+s+']')[0];
        if (bi != null) bi.id=s+'_'+len;
    }
    return $html.html();
}

$(document).on("click", ".open-updSyntaxModal", function () {
	$("#updSyntaxModal .modal-dialog")
	.modal("toggle")
	.css({'width': '80%', 'margin-left':'auto', 'margin-right':'auto'});

	var l_id = $(this).data('id');
	var r = getVNClass()
	if (r.length > 0) {
      var vnc = JSON.parse(r);
      var obs = null;
      var stx = null;
      for (i=0; i<vnc.frames.length; i++) {
    	  if (vnc.frames[i].id == l_id) {
    		  obs = vnc.frames[i];
    		  stx = obs.syntax[0];
    		  break;
    	  }
      }
      if (obs != null) {
        $(".modal-body #syntax_id").val( stx.id );
        $(".modal-body #id").val( stx.owner );
        $(".modal-body #frameName").text( obs.primary );
        $(".modal-body #isOrdered").prop( "checked", stx.isOrdered == "Yes" );
	  
        $(".modal-body .extrarow").remove();
	    for (i=0; i<stx.phrases.length; i++) {
	      $('<div/>', {
	        'class' : 'extrarow', html: GetHtml('.syntaxRowTemplate','.extrarow',['nr','type','value','restr'])
	        }).appendTo('.modal-body #syntaxfields');
	      $(".modal-body #nr_"+i).val( i );
	      $(".modal-body #nr_"+i).text( i );
	      $(".modal-body #type_"+i).val( stx.phrases[i].type );
	      $(".modal-body #value_"+i).val( stx.phrases[i].value );
	      l_restr = JSON.stringify(stx.phrases[i].restr)
	      $(".modal-body #restrs_"+i).val( verbalizeRestriction(l_restr, false) );
	    }
      }
	}
});

$(document).ready(function () {
	$('#addSyntaxRow').click(function () {
	  $('<div/>', {
	    'class' : 'extrarow', html: GetHtml('.syntaxRowTemplate','.extrarow',['nr','type','value','restr'])
	  }).hide().appendTo('.modal-body #syntaxfields').slideDown('slow');
	});
});

$(document).on("click", ".open-updSemanticsModal", function () {
	$("#updSemanticsModal .modal-dialog")
	.modal("toggle")
	.css({'width': '80%', 'margin-left':'auto', 'margin-right':'auto'});

	var l_id = $(this).data('id');
	var r = getVNClass()
	if (r.length > 0) {
      var vnc = JSON.parse(r);
      var obs = null;
      var stx = null;
      for (i=0; i<vnc.frames.length; i++) {
    	  if (vnc.frames[i].id == l_id) {
    		  obs = vnc.frames[i];
    		  stx = obs.semantics[0];
    		  break;
    	  }
      }
      if (obs != null) {
        $(".modal-body #semantics_id").val( stx.id );
        $(".modal-body #id").val( stx.owner );
        $(".modal-body #frameName").text( obs.primary );
	  
        $(".modal-body .extrarow").remove();
	    for (i=0; i<stx.predicates.length; i++) {
	      $('<div/>', {
	        'class' : 'extrarow', html: GetHtml('.semanticsRowTemplate','.extrarow',['invert','type','value'])
	        }).appendTo('.modal-body #semanticsfields');
	      $(".modal-body #invert_"+i).prop( "checked", stx.predicates[i].bool);
	      $(".modal-body #type_"+i).val( stx.predicates[i].type );
	      l_args = verbalizeSemanticsArgs(stx.predicates[i].args);
	      $(".modal-body #value_"+i).val( l_args );
	    }
      }
	}
});

$(document).ready(function () {
	$('#addSemanticsRow').click(function () {
	  $('<div/>', {
	    'class' : 'extrarow', html: GetHtml('.semanticsRowTemplate','.extrarow',['invert','type','value'])
	  }).hide().appendTo('.modal-body #semanticsfields').slideDown('slow');
	});
});

